//
//  FirstViewController.m
//  SectionChooseVC
//
//  Created by lujh on 2017/3/8.
//  Copyright © 2017年 lujh. All rights reserved.
//
#import "SectionChooseView.h"
#import "FirstViewController.h"
#import "LGLSearchBar.h"
#import "daibanTableViewCell.h"
#import "detailViewController.h"
#import "yjTableViewCell.h"
#import "dzTableViewCell.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "ckUnDonelistCell.h"
#import "dzggViewController.h"
@interface FirstViewController ()
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property(nonatomic,strong)NSDictionary * adic;
@property (nonatomic,strong)NSString *searchstr;
@property (nonatomic,strong)NSString *isSearching;

@end

@implementation FirstViewController

- (void)viewDidLoad {
      self.view.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
 LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(0, 10, KScreenWidth, 40) searchBarStyle:LGLSearchBarStyleDefault];
[searchBar setSearchBarBordeWidth:0.1 bordColor:[UIColor clearColor] bordRadius:0];
//[searchBar setSearchBarImage:@"search" scale:30];
        [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        NSLog(@"%@", searchText);
        if (searchText.length>0) {
        _isSearching = @"yes";
    _searchstr = searchText;
        [_tableView headerBeginRefreshing];

//        [self loadSearchData];
}
        else{
[self.view makeToast:@"搜索关键字不能为空"];
}

    }];
  
    [self.view addSubview:searchBar];
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50+5, KScreenWidth,self.view.height-kTopHeight-44-55-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];

_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
SectionChooseView *view = [SectionChooseView alloc];
view.buttonblock = ^{
[self loadData];
};
                 __weak typeof(self) weakSelf = self;

[self.tableView addHeaderWithCallback:^{

if([self.tableView isHeaderRefreshing])
{


}else{
        weakSelf.currentPage = 1;
         if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchData];
}else{
NSLog(@"1111");
        [weakSelf loadData]; //加载网络数据

}
}
    }];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((weakSelf.currentPage - 1)*KPageSize < weakSelf.totalCounts ){
        if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchMore];
}
     else {
     [weakSelf loadMore];
     }
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];
    [super viewDidLoad];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];


    // Do any additional setup after loading the view.
}
#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}
- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
_currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
     [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"backlogSearch" success:^(id JSON) {
    NSLog(@"%@",JSON);

      if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"待办文件(%@)",JSON[@"number"] ];
   if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"待办文件";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

}
- (void)loadSearchMore{
    __weak typeof(self) weakSelf = self;

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"backlogSearch" success:^(id JSON) {

       NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

   self.totalCounts =[JSON[@"number"] intValue];


        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{

// if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }
    [self.tableView headerBeginRefreshing];
_isSearching = @"no";
}
#pragma mark 加载网络数据
-(void)loadData{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    //requestWithURL
    [HttpTools requestWithURL:KexchgeneralURL arrays:array method:KTodoPagdMethod success:^(id JSON) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }

  _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];
         if(JSON[@"number"]){

     _titlename = [NSString stringWithFormat:@"待办文件(%@)",JSON[@"number"] ];
     if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
       }
        else{

      _titlename = @"待办文件";
      if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
       }
     
_adic= JSON[@"display"];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}

        [self.tableView reloadData];
    if (self.tableView .headerRefreshing) {
            [self.tableView headerEndRefreshing];

}
 if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有待办文件哦"];
        }
    } failure:^(NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    if (self.tableView .headerRefreshing) {
            [self.tableView headerEndRefreshing];

}
    }];
 
}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchgeneralURL arrays:array method:KTodoPagdMethod success:^(id JSON) {
        NSArray *array = JSON[@"data"];

  for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

     NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:60];

    return  titleFloat+10+10+20;


}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";

    daibanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[daibanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;


 }
 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
            NSDictionary *dic = self.dataArray[indexPath.row];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[storyBoard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
        detailVC.fileId = dic[@"unid"];
        if ([[NSString stringWithFormat:@"%@",dic[@"isSign"]] isEqualToString:@"1"]) {
            detailVC.isUnDoWork = NO;
        }else{
            detailVC.isUnDoWork = YES;
        }
      detailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:detailVC animated:YES];
    
}
@end
